package com.outsider.util;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outsider.news.dao.Zhihu;

public class ZhiHuUtil {
	public static final String NEWS_URL="http://daily.zhihu.com/story/";
	private static final String LATEST_NEWS_URL="http://news-at.zhihu.com/api/4/news/latest";
	
	
    public static void updateLatestNews(){
    	OkHttp3 httpUtil=OkHttp3.getInstance();
    	String json=httpUtil.get(LATEST_NEWS_URL);
    	
    	JSONObject body=JSONObject.parseObject(json);
    	JSONArray newsList=body.getJSONArray("stories");
    	JSONArray topStories=body.getJSONArray("top_stories");
    	//清空数据库
    	Zhihu.dao.deleteAll();
    	
    	for (int i=0;i<newsList.size();i++){
    	   JSONObject news=newsList.getJSONObject(i);
    	   Zhihu zhihu=new Zhihu();    	   
    	   zhihu.setID(news.getInteger("id"));
    	   zhihu.setImages(news.getJSONArray("images").getString(0));
    	   zhihu.setTitle(news.getString("title"));
    	   zhihu.save();
    	}
    	for (int i=0;i<topStories.size();i++){
     	   JSONObject news=topStories.getJSONObject(i);
     	   if (Zhihu.dao.findById(news.getInteger("id"))!=null) continue;
     	   Zhihu zhihu=new Zhihu(); 
     	   zhihu.setID(news.getInteger("id"));
     	   zhihu.setImages(news.getString("image"));
     	   zhihu.setTitle(news.getString("title"));
     	   zhihu.save();
     	}
    	Logger.getLogger("").info("Update zhihu News Complete");
    }
    public static Runnable getZhiHuTask(){
    	Runnable task=new Runnable() {
			public void run() {
				ZhiHuUtil.updateLatestNews();
			}
		};
		return task;
    }
}
